// Login Page
function validateForm(index) 
{
    var tmpacut = null;
    var tmppswd = null;
    var tmpname = null;
    var tmpcard = null;
    var tmpphne = null;

    if (index == 0)
    {
        tmpacut = document.forms[index]["useracut"].value;
        tmppswd = document.forms[index]["userpswd"].value;
        tmpname = document.forms[index]["username"].value;
        tmpcard = document.forms[index]["usercard"].value;
        tmpphne = document.forms[index]["userphne"].value;

        if (tmpacut == "" || tmpacut == null || 
            tmppswd == "" || tmppswd == null ||
            tmpname == "" || tmpname == null ||
            tmpcard == "" || tmpcard == null ||
            tmpphne == "" || tmpphne == null)
            return false;
    }
    else
    {
        tmpacut = document.forms[index]["lginacut"].value;
        tmppswd = document.forms[index]["lginpswd"].value;

        if (tmpacut == "" || tmpacut == null ||
            tmppswd == "" || tmppswd == null)
            return false;
    }
    return true;
}

function presubmit(index) 
{
	if (!validateForm(index)) 
	{
        alert("用户名/密码不能为空");
        return false;
    }
    document.forms[index].submit();
}

// Pswd chaning Page
function checkdouble(){
    var userpsw=$("#user_psw").val();
    var userpsw_again=$("#user_psw_again").val();
    var useracut=$("#user_acut").val();
    if(useracut=="")
    {
        alert("用户名不能为空！");
        return false;
    }
    if(userpsw==""||userpsw_again=="")
    {
        alert("密码不能为空!");
        return false;
    }
    if(userpsw!=userpsw_again){
        alert("两次输入的密码不匹配！");
        return false;
    }
    else
       return true;
}

$("#confirm_change").click(
    function () {
        if(checkdouble())
        {
            var useracut=$("#user_acut").val();
            var userpsw=$("#user_psw").val();
            var csrf_toke = jQuery("[name=csrfmiddlewaretoken]").val();
            var $form=$('#form_change')
            var url="/tickets/change_psw";

            var send_data={
                "useracut": useracut,
                "userpsw": userpsw,
                "csrfmiddlewaretoken": csrf_toke
            };


            $.ajax({
                url:url,
                type:"POST",
                data:send_data,
                dataType: 'json',
                success:function (data) {
                    console.log(data);
                    if(data["status"]!=200)
                    {
                        alert(
                        data["msg"]
                        );
                    }
                    else
                    {
                        alert(
                            data["msg"]
                        )
                        $form.attr('action',data.url);
                        console.log($form.attr('action'));
                        $form.submit();
                    }
                },
                error:function (error) {

                }
            })
        }
    }
)

// Result Page
function reserveBtn()
{
    $(document).ready(function(){
        $(".container--table td").off("click").click(function(){
        var tdSeq = $(this).parent().find("td").index($(this)[0]);
        var trSeq = $(this).parent().parent().find("tr").index($(this).parent()[0]);
        // var tCode = $(this).parents("tr").find("#tran_Code").text();
        // var tDate = $(this).parents("tr").find('#tran_Date').text();
        // alert("第" + (trSeq + 1) + "行，第" + (tdSeq + 1) + "列");
        var tCode = document.getElementById("tran_Code" + (trSeq + 1) / 2).innerHTML;
        var tDate = document.getElementById("tran_Date" + (trSeq + 1) / 2).innerHTML;
        // if (tCode != null)
        //     alert(tCode + " : " + tDate + " : " + (tdSeq + 1));
        reserve_send(tCode, tDate, tdSeq);
        });
    })
}

function reserve_send(tCode, tDate, tSeat)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            var res = JSON.parse(xmlhttp.responseText);
            if (res.result == 1)
            {
                alert(res.acut + "您已成功预定" + " : " + res.code + " : " + res.seat);
                location.reload();
            }
            else if (res.result == 2)
                alert("无法重复购票");
            else if (res.result == -1)
                alert("wrong type");
            else
                alert("Please login first");
        }
    }
    var seat_map = 
    {
        5:  "seat_busine",
        6:  "seat_firstt",
        7:  "seat_second",
        8:  "seat_advsft",
        9:  "seat_sftslp",
        10: "seat_bltslp",
        11: "seat_hrdslp",
        12: "seat_softer",
        13: "seat_harder",
        14: "seat_noleft"
    }
    xmlhttp.open("POST", "/tickets/ticket_reserve", true);
    var send_data = {"tran_code": tCode, "tran_date": tDate, "tran_seat": seat_map[tSeat]};
    var csrf_toke = jQuery("[name=csrfmiddlewaretoken]").val();
    xmlhttp.setRequestHeader('contenet-type', 'application/json');
    xmlhttp.setRequestHeader('X-CSRFToken', csrf_toke);
    xmlhttp.send(JSON.stringify(send_data));
}


function queryBtn()
{
    $(document).ready(function() {
        $('#btn_submit').off("click").click(function () {
            // alert($("#chooseStart").text()+"\n"+$("#chooseEnd").text()+"\n"+document.getElementById("chooseDate").value);
            query_send2(
                $("#chooseStart").text(), 
                $("#chooseEnd").text(), 
                document.getElementById("chooseDate").value, 
                $("#chooseOrder").text());
        });
    })
}

function query_send(station_start, station_arriv, tran_date)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            alert(xmlhttp.responseText);
            var res = JSON.parse(xmlhttp.responseText);
            if (res.result == -1)
                alert("参数缺失");
            else if (res.result == -2)
                alert("请求方法错误");
        }
    }
    
    xmlhttp.open("POST", "/tickets/query_inner", true);
    var send_data = {"station_start": station_start, "station_arriv": station_arriv, "tran_date": tran_date};
    var csrf_toke = jQuery("[name=csrfmiddlewaretoken]").val();
    xmlhttp.setRequestHeader('contenet-type', 'application/json');
    xmlhttp.setRequestHeader('X-CSRFToken', csrf_toke);
    xmlhttp.send(JSON.stringify(send_data));
}

function query_send2(station_start, station_arriv, tran_date, order_meth)
{
    var form = document.getElementById("innerform");
    var action = "/tickets/query_inner?station_start="+station_start+"&station_arriv="+station_arriv+"&tran_date="+tran_date+"&order_meth="+order_meth;
    form.setAttribute("action", action);
    form.setAttribute("method", "POST");
    form.submit();
}
// Personal Page

// Complaint Page
function complaint_get()
{
    var kind = document.getElementById("comt_kind");
    var comt_kind = kind.options[kind.selectedIndex].text;
    var comt_text = document.getElementById("describe").value;
    var comt_ctac = document.getElementById("email").value;
    // alert(comt_kind+comt_text+comt_ctac);
    complaint_send(comt_kind, comt_text, comt_ctac);
}

function complaint_send(comt_kind, comt_text, comt_ctac)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            var res = JSON.parse(xmlhttp.responseText);
            if (res.result == 1)
            {
                alert("尊敬的 " + res["user_name"] + " 我们已收到您的投诉");
                location.reload();
            } 
            else if (res.result == -1)
            {
                alert("系统错误:\n" + res["content"]);
            }
            else if (res.result == 0)
            {
                alert("系统测试:\n" + res["content"]);
            }
        }
    }
    // alert(comt_kind+comt_text+comt_ctac);
    xmlhttp.open("POST", "/tickets/complaint_record", true);
    var dateObj = new Date();
    var comt_date = dateObj.getFullYear() + "-" + (dateObj.getMonth() + 1) + "-" + dateObj.getDate();
    var send_data = 
    {
        "comt_kind": comt_kind, 
        "comt_text": comt_text, 
        "comt_ctac": comt_ctac,
        "comt_date": comt_date
    };
    var csrf_toke = jQuery("[name=csrfmiddlewaretoken]").val();
    xmlhttp.setRequestHeader('contenet-type', 'application/json');
    xmlhttp.setRequestHeader('X-CSRFToken', csrf_toke);
    xmlhttp.send(JSON.stringify(send_data));
}

// Manager Page
function complaint_reply(element)
{
    // alert(element.id);
    var comt_uuid = element.id;
    var rply_text = document.getElementById(("reply_text_"+comt_uuid)).value;
    // alert(reply_text);
    var xmlhttp;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            var res = JSON.parse(xmlhttp.responseText);
            if (res.result == 0)
            {
                location.reload();
            } 
            else if (res.result == -1)
            {
                alert("Wrong Method");
            }
            else if (res.result == -2)
            {
                alert("User not login");
            }
            else if (res.result == -3)
            {
                alert("Arugument not received")
            }
        }
    }
    // alert(comt_kind+comt_text+comt_ctac);
    xmlhttp.open("POST", "/tickets/comt_reply", true);
    var send_data = 
    {
        "comt_uuid": comt_uuid, 
        "rply_text": rply_text
    };
    var csrf_toke = jQuery("[name=csrfmiddlewaretoken]").val();
    xmlhttp.setRequestHeader('contenet-type', 'application/json');
    xmlhttp.setRequestHeader('X-CSRFToken', csrf_toke);
    xmlhttp.send(JSON.stringify(send_data));
}